import pdfplumber
import pandas as pd
import re, subprocess

def parse_domain(domain):
    ipv4_strict_pattern = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
    status, res = subprocess.getstatusoutput(f"ping {domain}")
    print(f'状态：{status}')
    print(f'执行结果：{res}')
    if status:
        ips = re.findall(ipv4_strict_pattern, res)

        #域名能解析ip处理
        if ips:
            for ip in list(set(ips)):
                print(ip)
            return ip
        else:
            return


def pdf_read(name):
    with pdfplumber.open("C:\software\pythonProject\HW2024-08-01微步威胁情报合集.pdf") as pdf:
        # 获取文档的总页数
        total_pages = len(pdf.pages)

        # 遍历每一页
        for page_number in range(total_pages):
            # 获取当前页
            page = pdf.pages[page_number]
            text = page.extract_text()
            # print(text)
            print(f"-----------开始匹配第{page}页---------------")
            ipv4_strict_pattern = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
            # 定义一个简单的域名正则表达式
            # 注意：这个正则表达式并不完美，因为它没有考虑所有可能的TLD长度或字符集
            # 它也假设域名不包含非ASCII字符（如国际化域名IDN）
            domain_pattern = r'[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}'
            no_affect_domain = ["www.threatbook.cn", "threatbook.cn", "www.threatbook.com", "threatbook.com"]
            # 匹配出ip地址
            # for ip in re.findall(ipv4_strict_pattern, text):
            #     print(f"匹配出的ip:{ip}")

            # 匹配出域名
            for domain in re.findall(domain_pattern, text):
                if domain not in no_affect_domain:
                    print(f"匹配出的域名：{domain}")
                    print(f"解析出的ip：{parse_domain(domain)}")

            print(f"-----------结束匹配第{page}页---------------")




# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    pdf_read('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
